package com.cc.alltype;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectUtils {
    /**
     * 检测类中是否含有指定名称的属性，会递归向上追溯所有父类私有属性
     * @param clazz 类的类型
     * @param propertyName 属性名称
     * @return
     */
    public static boolean hasField(Class clazz, String propertyName) {
        while (clazz != null) {
            try {
                Field field = clazz.getDeclaredField(propertyName);
                if(null != field) return true;
            } catch (NoSuchFieldException e) {
                clazz = clazz.getSuperclass();
            }
        }
        return false;
    }

    /**
     * 检测类中是否含有指定名称的方法，会递归向上追溯所有父类私有方法
     * @param clazz 类的类型
     * @param methodName 属性名称
     * @return
     */
    public static boolean hasMethod(Class clazz, String methodName) {
        while (clazz != null) {
            try {
                Method method = clazz.getDeclaredMethod(methodName);
                if(null != method) return true;
            } catch (NoSuchMethodException e) {
                clazz = clazz.getSuperclass();
            }
        }
        return false;
    }

    public class Test{
        private Integer id;
        private String name;
        private String getName(){
            return "Test 的方法 getName";
        }
    }

    public class Test1 extends Test {
        private String category;
        private String getCategory(){
            return "Test1 的方法 getCategory";
        }
    }
    public static void main(String[] args) {
//        boolean category = ReflectUtils.hasField(Test1.class, "category");
//        boolean category11 = ReflectUtils.hasField(Test1.class, "category11");
//        boolean name = ReflectUtils.hasField(Test1.class, "name");
//        boolean name11 = ReflectUtils.hasField(Test1.class, "name11");
//        System.out.println("属性category是否存在：" + category + ",属性category11是否存在：" + category11
//                + "，属性name是否存在：" + name + ",属性name11是否存在：" + name11);

        boolean getCategory = ReflectUtils.hasMethod(Test1.class, "getCategory");
        boolean getCategory11 = ReflectUtils.hasMethod(Test1.class, "getCategory11");
        boolean getName = ReflectUtils.hasMethod(Test1.class, "getName");
        boolean getName11 = ReflectUtils.hasMethod(Test1.class, "getName11");
        System.out.println("方法getCategory是否存在：" + getCategory + ",属性getCategory11是否存在：" + getCategory11
                + "，属性getName是否存在：" + getName + ",属性getName11是否存在：" + getName11);
    }
}
